package com.briup.jd2407cms.service.impl;

import cn.hutool.core.util.ObjUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.briup.jd2407cms.domain.Comment;
import com.briup.jd2407cms.domain.DTO.CommentDeleteParam;
import com.briup.jd2407cms.domain.DTO.CommentQueryParam;
import com.briup.jd2407cms.domain.Subcomment;
import com.briup.jd2407cms.domain.User;
import com.briup.jd2407cms.domain.extend.CommentExtend;
import com.briup.jd2407cms.exception.ServiceException;
import com.briup.jd2407cms.mapper.ArticleMapper;
import com.briup.jd2407cms.mapper.UserMapper;
import com.briup.jd2407cms.service.CommentService;
import com.briup.jd2407cms.mapper.CommentMapper;
import com.briup.jd2407cms.service.SubcommentService;
import com.briup.jd2407cms.util.result.ResultCode;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

/**
* @author jay
* @description 针对表【cms_comment】的数据库操作Service实现
* @createDate 2024-11-18 14:40:14
*/
@Service
public class CommentServiceImpl extends ServiceImpl<CommentMapper, Comment>
    implements CommentService{
    @Autowired
    private CommentMapper commentMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private SubcommentService subcommentService;
    @Autowired
    private ArticleMapper articleMapper;

    @Override
    @Transactional
    public IPage<CommentExtend> page(CommentQueryParam param) {
        if (ObjUtil.isEmpty(param) || ObjUtil.isEmpty(param.getPageNum()) ||ObjUtil.isEmpty(param.getPageSize())){
            log.error("分页条件查询评论的参数为空");
            throw new ServiceException(ResultCode.PARAM_IS_BLANK);
        }

    IPage<Comment> page = new Page<>(param.getPageNum(), param.getPageSize());
    LambdaQueryWrapper<Comment> lqw = new LambdaQueryWrapper<>();
        lqw.eq(!StrUtil.isEmpty(param.getArticleId()), Comment::getArticleId, param.getArticleId())
            .eq(!StrUtil.isEmpty(param.getUserId()), Comment::getUserId, param.getUserId())
            .like(!StrUtil.isEmpty(param.getKeyword()), Comment::getContent, param.getKeyword())
            .ge(!ObjUtil.isEmpty(param.getStartTime()), Comment::getPublishTime, param.getStartTime())
            .le(!ObjUtil.isEmpty(param.getEndTime()), Comment::getPublishTime, param.getEndTime())
            .orderByDesc(Comment::getPublishTime);
        super.page(page,lqw);

        // 拼接user和subComment
        List<Comment> records = page.getRecords();
        ArrayList<CommentExtend> list = new ArrayList<>();
        for (Comment comment : records) {
            // 拷贝comment到commentExtend
            CommentExtend commentExtend = new CommentExtend();
            BeanUtils.copyProperties(comment,commentExtend);
            // 拼接User
            String userId = String.valueOf(comment.getUserId());
            User user = userMapper.selectById(userId);
            // 额外注释密码，不能返回给前端
            user.setPassword(null);
            commentExtend.setUser(user);

            // 拼接subComment
            List<Subcomment> subcomments = subcommentService.selectByParentId(String.valueOf(comment.getId()));
            commentExtend.setSubcomment(subcomments);

            list.add(commentExtend);
        }
        return new Page<CommentExtend>().setRecords(list)
                .setTotal(page.getTotal())
                .setCurrent(page.getCurrent());

//        return commentMapper.page(page, param.getArticleId().trim(), param.getUserId().trim(),
//                param.getKeyword().trim(), param.getStartTime(), param.getEndTime());
    }

    @Override
    @Transactional
    public boolean saveComment(Comment comment) {
        // 1.参数判断
        if (ObjUtil.isEmpty(comment)){
            log.error("要新增的一级评论为空");
            throw new ServiceException(ResultCode.PARAM_IS_BLANK);
        }

        // 2.用户存在及禁用状态判断
        User user = userMapper.selectById(comment.getUserId());
        if (ObjUtil.isEmpty(user)){
            log.error("新增一级评论的用户不存在");
            throw new ServiceException(ResultCode.USER_NOT_EXIST);
        }
        if ("禁用".equals(user.getStatus())) {
            log.error("账号已被禁用，无法评论");
            throw new ServiceException(ResultCode.USER_ACCOUNT_FORBIDDEN);
        }

        // 3.文章存在判断
        if (ObjUtil.isEmpty(articleMapper.selectById(comment.getArticleId()))){
            log.error("要评论的文章不存在");
            throw new ServiceException(ResultCode.ARTICLE_NOT_EXIST);
        }

        // 4.发表时间准备
        comment.setPublishTime(LocalDateTime.now());

        // 5.发表评论
        return super.save(comment);
    }

    @Override
    @Transactional
    public boolean deleteById(CommentDeleteParam param) {
        // 1.参数判断
        String id = param.getId();
        Integer type = param.getType();
        if(ObjUtil.isEmpty(param) || type == null || StrUtil.isEmpty(id)){
            log.error("传入的删除参数为空");
            throw new ServiceException(ResultCode.PARAM_IS_BLANK);
        }

        // 2.类型判断
        if (type == 1){
            // 需要删除的是1级评论
            if (ObjUtil.isEmpty(commentMapper.selectById(id))){
                log.error("要删除的一级评论不存在");
                throw new ServiceException(ResultCode.COMMENT_NOT_EXIST);
            }

            // 级联删除
            if (!super.removeById(id) || !subcommentService.deleteByParentId(id)){
                log.error("级联删除一级评论失败");
                throw new ServiceException(ResultCode.FAIL);
            }
        } else if(type == 2){
            // 需要删除的是2级评论
            if (ObjUtil.isEmpty(subcommentService.getById(id))){
                log.error("要删除的二级评论不存在");
                throw new ServiceException(ResultCode.COMMENT_NOT_EXIST);
            }

            // 二级评论删除
            if (!subcommentService.removeById(id)){
                log.error("删除二级评论失败");
                throw new ServiceException(ResultCode.FAIL);
            }
        } else {
            log.error("要删除的评论类型无效");
            throw new ServiceException(ResultCode.PARAM_IS_INVALID);
        }
        return true;
    }

    @Override
    @Transactional
    public void deleteInBatch(List<CommentDeleteParam> list) {
        for (CommentDeleteParam param : list) {
            deleteById(param);
        }
    }
}




